package com.chookss.home.search.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.document.DocumentPreviewActivity;
import com.chookss.home.document.DownloadService;
import com.chookss.home.entity.DocunmentEntity;
import com.chookss.home.search.entity.SearchAllEntity;
import com.chookss.tools.MyToast;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.google.gson.reflect.TypeToken;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.annotations.Nullable;

public class SearchDataAdapter extends BaseQuickAdapter<SearchAllEntity.DataBean.ListBean, BaseViewHolderEx> {
    private Context context;
    private int width, height;
    private String key, tag;

    public SearchDataAdapter(int layoutResId, Context context, @Nullable List<SearchAllEntity.DataBean.ListBean> data, String tag) {
        super(layoutResId, data);
        this.context = context;
        this.tag = tag;

    }

    @Override
    protected void convert(BaseViewHolderEx helper, SearchAllEntity.DataBean.ListBean item) {
        TextView tvTiltle = helper.getView(R.id.tvSearchDataTitle);
        TextView tvSearchProvider = helper.getView(R.id.tvSearchDataProvider);
        TextView tvSearchKeywords = helper.getView(R.id.tvSearchDataKeywords);
        ImageView ivSearchData = helper.getView(R.id.ivSearchData);
        ProgressBar progressBar = helper.getView(R.id.progressBar);
        String fileType = item.getFileType();//文件类型1--word 2 --excel 3--PPT  4pdf

        if ("1".equals(fileType)) {
            Glide.with(context).load(R.drawable.icon_qj_w).into(ivSearchData);
        } else if ("2".equals(fileType)) {
            Glide.with(context).load(R.drawable.icon_qj_x).into(ivSearchData);
        } else if ("3".equals(fileType)) {
            Glide.with(context).load(R.drawable.icon_qj_p).into(ivSearchData);
        } else if ("4".equals(fileType)) {
            Glide.with(context).load(R.drawable.icon_qj_pdf_ss).into(ivSearchData);
        } else {
            Glide.with(context).load(R.drawable.icon_qj_mr_ss).into(ivSearchData);
        }
        if (item.getProgress() == 0 || item.getProgress() == 100) {
            progressBar.setVisibility(View.GONE);
        } else {
            progressBar.setVisibility(View.VISIBLE);
            progressBar.setProgress(item.getProgress());
        }
        tvTiltle.setText(Utils.matcherSearchTitle(context.getResources().getColor(R.color.main_color), item.getDataTitle(), key));
        if (!Utils.isNull(item.getUploadPersonName())) {
            tvSearchProvider.setVisibility(View.VISIBLE);
            tvSearchProvider.setText("提供者：");
            tvSearchProvider.append(Utils.matcherSearchTitle(context.getResources().getColor(R.color.main_color), item.getUploadPersonName(), key));
        } else {
            tvSearchProvider.setVisibility(View.GONE);
        }
        if (!Utils.isNull(item.getKeyWord())) {
            if (item.getKeyWord().contains(key)) {
                tvSearchKeywords.setVisibility(View.VISIBLE);
                tvSearchKeywords.setText("关键词：");
                tvSearchKeywords.append(Utils.matcherSearchTitle(context.getResources().getColor(R.color.main_color), item.getKeyWord(), key));
            } else {
                tvSearchKeywords.setVisibility(View.GONE);
            }
        } else {
            tvSearchKeywords.setVisibility(View.GONE);
        }
        helper.getItemView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Urls.antiShake.check()) {
                    return;
                }
                requestSTORAGE(item, tvTiltle.getText().toString(), helper.getItemPosition());
            }
        });
    }

    private void requestSTORAGE(SearchAllEntity.DataBean.ListBean entity, String retitle, int rePosition) {
        XXPermissions.with(context)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {
                            getDocunmentDetail(entity, retitle, rePosition);
                        } else {
                            MyToast.show("存储未被授权，请先去权限设置里面授权");
                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(context, denied, quick);
                    }
                });
    }

    private void getDocunmentDetail(SearchAllEntity.DataBean.ListBean entity, String docTitle, int docPosition) {
        Map<String, String> map = new HashMap<>();
        map.put("dataCode", entity.getDataCode());
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<DocunmentEntity>>() {
        }.getType(), null, Urls.getDetail, SignUtils2.makeSignStr(map), false, new ObserverCallback<DocunmentEntity>() {
            @Override
            public void onSuccess(DocunmentEntity newData) {
                if (newData != null) {
                    openFile(newData, docTitle, docPosition,entity.isError());
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void openFile(DocunmentEntity entity, String title, int position,boolean isError) {
        if (!Utils.isNull(entity.getDataUrl())) {
            String url, name, fileUrl, urls;
            url = entity.getDataUrl();
            urls = url.split("\\?")[0];
            fileUrl = urls.substring(urls.lastIndexOf("/") + 1, urls.length());
            if (MyApp.downloadFiles.contains(title)||!MyApp.mIsInitTBSSuccess||isError) {
                if(!MyApp.docunmentOpen) {
                    Intent intent = new Intent(context, DocumentPreviewActivity.class);
                    intent.putExtra("fileUrl", fileUrl);
                    intent.putExtra("fileName", title);
                    intent.putExtra("dataCode", entity.getDataCode());
                    context.startActivity(intent);
                }
            } else {
//                    downTask(url, title, entity, position);
                entity.setProgress(1);
                notifyItemChanged(position);
                Intent intent = new Intent(context, DownloadService.class);
                intent.putExtra("fileUrl", fileUrl);
                intent.putExtra("fileName", title);
                intent.putExtra("url", url);
                intent.putExtra("dataCode", entity.getDataCode());
                intent.putExtra("position", position);
                intent.putExtra("tag", tag);
                context.startService(intent);
            }

        }
    }

    public void setKey(String key) {
        this.key = key;
    }
}
